package top.zywork.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import top.zywork.annotation.SysLog;
import top.zywork.common.BeanUtils;
import top.zywork.common.BindingResultUtils;
import top.zywork.common.StringUtils;
import top.zywork.dto.GraphicDTO;
import top.zywork.dto.PagerDTO;
import top.zywork.dto.GraphicLinkDTO;
import top.zywork.enums.PrintSpecEnum;
import top.zywork.ext.dos.GraphicLinkExtDO;
import top.zywork.ext.service.GraphicExtService;
import top.zywork.ext.service.GraphicLinkExtService;
import top.zywork.query.GraphicLinkQuery;
import top.zywork.service.GraphicLinkService;
import top.zywork.vo.ResponseStatusVO;
import top.zywork.vo.PagerVO;
import top.zywork.vo.GraphicLinkVO;
import top.zywork.wx.response.GraphicSpecResponse;
import top.zywork.wx.save.GraphicSpecSave;

import javax.xml.ws.Response;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * GraphicLinkController控制器类<br/>
 *
 * 创建于2020-12-02<br/>
 *
 * @author http://ljyanimo.com 刘金泳
 * @version 1.0
 */
@RestController
@RequestMapping("/graphic-link")
@Slf4j
public class GraphicLinkController extends BaseController {

    private GraphicLinkService graphicLinkService;

    @Autowired
    private GraphicExtService graphicExtService;

    @Autowired
    private GraphicLinkExtService graphicLinkExtService;

    /**
     * 查询组合链的价格
     * @param id
     * @param graphicSpecSave
     * @param bindingResult
     * @return
     */
    @PostMapping("any/specPrice/{id}")
    public ResponseStatusVO specPrice(@PathVariable("id") Integer id, @RequestBody GraphicSpecSave graphicSpecSave, BindingResult bindingResult){
        if (bindingResult.hasErrors()) {
            return ResponseStatusVO.dataError(BindingResultUtils.errorString(bindingResult), null);
        }
        GraphicLinkExtDO one = graphicLinkExtService.getOne(new QueryWrapper<GraphicLinkExtDO>().eq("graphic_id", id).eq("zzlx", graphicSpecSave.getZzlx()).eq("ys", graphicSpecSave.getYs()).eq("dsm", graphicSpecSave.getDsm()));
        return ResponseStatusVO.ok("查询成功",one);
    }

    /**
     * 返回当前学校的规格东西
     * @param id
     * @return
     */
    @GetMapping("any/spec/{id}")
    public ResponseStatusVO spec(@PathVariable("id") Integer id){
        PrintSpecEnum[] values = PrintSpecEnum.values();
        Map<String,Object> map = new HashMap<>(16);
        for(PrintSpecEnum printSpecEnum : values){
            List<GraphicLinkExtDO> linkExtDOS = graphicLinkExtService.list(new QueryWrapper<GraphicLinkExtDO>()
                    .select(printSpecEnum.getKey())
                    .eq("graphic_id", id)
                    .isNotNull(printSpecEnum.getKey())
                    .groupBy(printSpecEnum.getKey()));

            List<GraphicSpecResponse> list;
            list = linkExtDOS.stream().map(e->{
                GraphicSpecResponse graphicSpecResponse = new GraphicSpecResponse();
                Field name = null;
                try {
                    name = e.getClass().getDeclaredField(printSpecEnum.getKey());
                } catch (NoSuchFieldException e1) {
                    e1.printStackTrace();
                }
                name.setAccessible(true);

                try {
                    graphicSpecResponse.setName(name.get(e).toString());
                } catch (IllegalAccessException e1) {
                    e1.printStackTrace();
                }
                return graphicSpecResponse;
            }).collect(Collectors.toList());

            map.put(printSpecEnum.getKey(),list);
        }
        return ResponseStatusVO.ok("查询成功",map);
    }


    @PostMapping("admin/save")
    @SysLog(description = "后台保存GraphicLinkVO")
    public ResponseStatusVO save(@RequestBody @Validated GraphicLinkVO graphicLinkVO, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResponseStatusVO.dataError(BindingResultUtils.errorString(bindingResult), null);
        }
        graphicLinkService.save(BeanUtils.copy(graphicLinkVO, GraphicLinkDTO.class));
        return ResponseStatusVO.ok("添加成功", null);
    }

    @PostMapping("admin/batch-save")
    @SysLog(description = "后台批量保存GraphicLinkVO")
    public ResponseStatusVO saveBatch(@RequestBody @Validated List<GraphicLinkVO> graphicLinkVOList, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResponseStatusVO.dataError(BindingResultUtils.errorString(bindingResult), null);
        }
        graphicLinkService.saveBatch(BeanUtils.copyListObj(graphicLinkVOList, GraphicLinkDTO.class));
        return ResponseStatusVO.ok("批量添加成功", null);
    }

    @GetMapping("admin/remove/{id}")
    @SysLog(description = "后台删除GraphicLinkVO")
    public ResponseStatusVO removeById(@PathVariable("id") Long id) {
        graphicLinkService.removeById(id);
        return ResponseStatusVO.ok("删除成功", null);
    }

    @PostMapping("admin/batch-remove")
    @SysLog(description = "后台批量删除GraphicLinkVO")
    public ResponseStatusVO removeByIds(@RequestBody String[] ids) {
        graphicLinkService.removeByIds(StringUtils.strArrayToLongArray(ids));
        return ResponseStatusVO.ok("批量删除成功", null);
    }

    @PostMapping("admin/update")
    @SysLog(description = "后台更新GraphicLinkVO")
    public ResponseStatusVO update(@RequestBody @Validated GraphicLinkVO graphicLinkVO, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResponseStatusVO.dataError(BindingResultUtils.errorString(bindingResult), null);
        }
        int updateRows = graphicLinkService.update(BeanUtils.copy(graphicLinkVO, GraphicLinkDTO.class));
        if (updateRows == 1) {
            return ResponseStatusVO.ok("更新成功", null);
        } else {
            return ResponseStatusVO.dataError("数据版本号有问题，在此更新前数据已被更新", null);
        }
    }

    @PostMapping("admin/batch-update")
    @SysLog(description = "后台批量更新GraphicLinkVO")
    public ResponseStatusVO updateBatch(@RequestBody @Validated List<GraphicLinkVO> graphicLinkVOList, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResponseStatusVO.dataError(BindingResultUtils.errorString(bindingResult), null);
        }
        graphicLinkService.updateBatch(BeanUtils.copyListObj(graphicLinkVOList, GraphicLinkDTO.class));
        return ResponseStatusVO.ok("批量更新成功", null);
    }

    @PostMapping("admin/active")
    @SysLog(description = "后台激活或冻结GraphicLinkVO")
    public ResponseStatusVO active(@RequestBody GraphicLinkVO graphicLinkVO) {
        graphicLinkService.update(BeanUtils.copy(graphicLinkVO, GraphicLinkDTO.class));
        return ResponseStatusVO.ok("激活或冻结成功", null);
    }

    @PostMapping("admin/batch-active")
    @SysLog(description = "后台批量激活或冻结GraphicLinkVO")
    public ResponseStatusVO activeBatch(@RequestBody @Validated List<GraphicLinkVO> graphicLinkVOList) {
        graphicLinkService.updateBatch(BeanUtils.copyListObj(graphicLinkVOList, GraphicLinkDTO.class));
        return ResponseStatusVO.ok("批量激活或冻结成功", null);
    }

    @GetMapping("admin/one/{id}")
    public ResponseStatusVO getById(@PathVariable("id") Long id) {
        GraphicLinkVO graphicLinkVO = new GraphicLinkVO();
        Object obj = graphicLinkService.getById(id);
        if (obj != null) {
            graphicLinkVO = BeanUtils.copy(obj, GraphicLinkVO.class);
        }
        return ResponseStatusVO.ok("查询成功", graphicLinkVO);
    }

    @GetMapping("admin/all")
    public ResponseStatusVO listAll() {
        PagerDTO pagerDTO = graphicLinkService.listAll();
        PagerVO pagerVO = BeanUtils.copy(pagerDTO, PagerVO.class);
        pagerVO.setRows(BeanUtils.copyList(pagerDTO.getRows(), GraphicLinkVO.class));
        return ResponseStatusVO.ok("查询成功", pagerVO);
    }

    @PostMapping("admin/all-cond")
    public ResponseStatusVO listAllByCondition(@RequestBody GraphicLinkQuery graphicLinkQuery) {
        PagerDTO pagerDTO = graphicLinkService.listAllByCondition(graphicLinkQuery);
        PagerVO pagerVO = BeanUtils.copy(pagerDTO, PagerVO.class);
        pagerVO.setRows(BeanUtils.copyList(pagerDTO.getRows(), GraphicLinkVO.class));
        return ResponseStatusVO.ok("查询成功", pagerVO);
    }

    @PostMapping("admin/pager-cond")
    public ResponseStatusVO listPageByCondition(@RequestBody GraphicLinkQuery graphicLinkQuery) {
        PagerDTO pagerDTO = graphicLinkService.listPageByCondition(graphicLinkQuery);
        PagerVO pagerVO = BeanUtils.copy(pagerDTO, PagerVO.class);

        List<Object> list;

        list = pagerDTO.getRows().stream().map(e->{
            GraphicLinkDTO graphicLinkDTO = (GraphicLinkDTO)e;
            graphicLinkDTO.setGraphicValue(graphicExtService.getById(graphicLinkDTO.getGraphicId()).getTwdmc());
            return graphicLinkDTO;
        }).collect(Collectors.toList());
        pagerVO.setRows(list);
        return ResponseStatusVO.ok("查询成功", pagerVO);
    }

    @Autowired
    public void setGraphicLinkService(GraphicLinkService graphicLinkService) {
        this.graphicLinkService = graphicLinkService;
    }
}
